from uuid import uuid1
import datetime
if __name__ == '__main__':
    from conn_mysql import ConnectMysql
else:
    from .conn_mysql import ConnectMysql
import pymysql

class MysqlApi(ConnectMysql):

    def insert_company_for_openid(self, openid):
        '''插入openid到数据库存中'''

        sql = "INSERT INTO company(openid) VALUES (%s)"

        return self.insert_info(sql, (openid,))

    def select_company_for_openid(self, openid=None, company_id=None):
        '''传入openid,或者company_id取出company表的所有信息'''
        if all([openid, company_id]) and (not any([openid, company_id])):

            raise ValueError('openid和company_id只能给一个参数')

        if openid:
            sql = "SELECT * FROM company WHERE openid=%s"
            result = self.select_one(sql, (openid,))

        elif company_id:
            sql = "SELECT * FROM company WHERE id=%s"
            result = self.select_one(sql, (company_id,))

        return result

    def insert_or_select_company_for_openid(self, openid):
        '''如果company表中有openid则取出，否则插入openid到company表中'''

        select_result = self.select_company_for_openid(openid)

        if not select_result:

            return self.insert_company_for_openid(openid)

        return select_result

    def select_need(self, company_id):
        '''传入company_id获取对应的need表中的对应的信息'''

        sql = "SELECT * FROM need WHERE company_id=%s"

        result = self.select_all(sql, (company_id,))

        return result

    def select_last_need(self, company_id):
        '''传入company_id获取对应的need表中的对应的信息'''

        sql = "SELECT * FROM need WHERE company_id=%s ORDER BY id DESC LIMIT 0,1"

        result = self.select_all(sql, (company_id,))

        if not result:

            return None

        return result[0]

    def company_status(self, openid):
        '''传入openid反回该账号对应的状态

        return: 
            {
                'company_state': 1, #代表是否注册 1代表可以，0代表不可以
                'company_update_state': 0, #代表是否可发布：1代表可以发布，0代表不可以
                'company_id':
                'openid':
            }
        
        '''
        result_company = self.insert_or_select_company_for_openid(openid)

        if isinstance(result_company, int):#如里result_company返回的是整数则表示第一次登录，原来没记录openid

            return {
                'company_state': 0,
                'company_update_state': 0,
                'company_id': result_company,
                'openid': openid
            }
        
        #如果openid库存中有   
        phone = result_company.get('phone')
        if not phone:#如果phone没有值代表还没有注册信息

            return {

                'company_state': 0,
                'company_update_state': 0,
                'company_id': result_company.get('id'),
                'openid': openid

            }

        # result_need = self.select_need(result_company.get('id'))

        result_need = self.select_last_need(result_company.get('id'))

        if not result_need:#result_need返回None证明没注册过
            return {
                'company_state': 1,
                'company_update_state': 0,
                'company_id': result_company.get('id'),
                'openid': openid
            }

        if result_need['regedate'] + datetime.timedelta(days=1) >= datetime.datetime.now():

            company_update_state = 0

        else:

            company_update_state = 1

        return {
                'company_state': 1,
                'company_update_state': company_update_state,
                'company_id': result_company.get('id'),
                'openid': openid
            }

    def select_need_all(self, page=None, limit=None, party=None):
        '''need表的查函数'''

        if page == None:

            page = 1
        
        if limit == None:

            limit = 20

        
        page = int(page)
        limit = int(limit)

        if party == None:

            sql = '''
                SELECT * FROM need LIMIT %s,%s
            '''

            result = self.select_all(sql, ((page - 1) * limit, limit))

        else:
            sql = '''
                SELECT * FROM need WHERE party=%s LIMIT %s,%s
            '''
            result = self.select_all(sql, (party, (page - 1) * limit, limit))

        return result

    def select_need(self, need_id):

        sql = "select * from need where id=%s"

        result = self.select_one(sql, (need_id,))

        return result
    
    def select_need_pay(self, need_id, company_id):
        '''检测付费情况1为付费0为没付费'''

        sql = 'select * from pay_log where company_id=%s and need_id=%s and pay_status=1'

        result = self.select_one(sql, (company_id, need_id))

        if result:

            return 1
        else:
            return 0

    def register(self, **info):

        sql='''
            UPDATE company SET company_name=%s, linkman=%s, phone=%s WHERE openid=%s
        '''
        sql_ = '''
            INSERT INTO need(company_id, need, party) VALUES (%s, %s, %s);
        '''

        self.update_info(sql, (info['company_name'], info['linkman'], info['phone'], info['openid']))

        self.insert_info(sql_, (info['company_id'], info['need'], info['party']))

    def insert_pay_log(self, company_id, need_id, pay_status=None):

        if pay_status == None:

            sql = "INSERT INTO pay_log(company_id, need_id) VALUES (%s, %s)"

            self.insert_info(sql, (company_id, need_id))
        else:

            sql = "INSERT INTO pay_log(company_id, need_id, pay_status) VALUES (%s, %s, %s)"

            self.insert_info(sql, (company_id, need_id, pay_status))

    def update_need(self, company_id, need, party):
        sql = 'INSERT INTO need(company_id, need, party) VALUES (%s,%s,%s)'
        self.insert_info(sql, (company_id, need, party))
    # m.update_need(session['company_id'], need, party)

    def select_need_pay_all(self, company_id):

        sql = 'select * from pay_log where company_id=%s and pay_status=1'

        result = self.select_all(sql, (company_id,))

        return result



if __name__ == '__main__':
    
    x = MysqlApi()

    x.company_status('123')
    






    # def __init__(self):

    #     super().__init__()

    # def select_for_company_id(self, ID):
    #     '''传入company_id获取company表中对应的信息'''

    #     sql = "SELECT * FROM company WHERE id=%s"

    #     return self.select_one(sql, (ID,))
    
    # def update_need(self, company_id, need):
    #     '''用户发布需求'''
    #     sql = "UPDATE company SET need=%s"

    #     return self.update_info(sql, (need, company_id))

    # def select_user(self, phone, pass_word):#传入用户名和密码找到对应的数据
    #     '''#传入用户名和密码找到company表中对应的数据'''

    #     sql = 'SELECT * FROM company WHERE phone=%s and pass_word=%s'

    #     return self.select_one(sql, (phone, pass_word))

    # def select_openid(self, openid):#传入token返回token表对应的数据

    #     '''传入openid返回openid表对应的数据'''

    #     sql = "SELECT * FROM openid WHERE openid=%s"

    #     return self.select_one(sql, (openid))

    # def insert_token(self, token, company_id):#传入公司ID,在token表中增加一个token值
    #     '''传入公司ID,在token表中增加一个token值
    #     company_id: int #公司的id
    #     return: 0  #回定的
    #     '''

    #     sql = 'INSERT INTO token(token, company_id) VALUES (%s, %s)'

    #     return self.insert_info(sql, (token, company_id))

    # def insert_register(self, info_dict):
    #     '''向company表中插入注册数据
    #     '''

    #     args = list(info_dict.values())


    #     if not all(args):

    #         return {

    #             "status": -1,
    #             "errorCode": 21,
    #             "errorMsg": "确少参数",
    #             "resultBody": None          
    #         }

    #     sql = '''INSERT INTO company
    #     (company_name, product_name, need, linkman, phone, party, pass_word, openid)
    #     values
    #     (%s,%s,%s,%s,%s,%s,%s,%s);       
    #     '''
    #     try:
    #         self.insert_info(sql, args)

    #     except pymysql.err.IntegrityError as e:

    #         if e.args[0] == 1062:

    #             return {
    #                 "status": -1,
    #                 "errorCode": e.args[0],
    #                 "errorMsg": e.args[1],
    #                 "resultBody": None          
    #             }
    #     else:

    #         return {

    #                 "status": 1,
    #                 "errorCode": None,
    #                 "errorMsg": None,
    #                 "resultBody": "注册成功"          
    #             }





    
